﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace WJ.Infrastructure.Log
{
    public class SystemLog : ISystemLog
    {
        private List<LogItem> logList = new List<LogItem>();

        public Action<List<LogItem>> SaveMode { get; set; }

        public void Exception(System.Exception e)
        {
            if (e != null)
            {
                logList.Add(new LogItem("错误信息：" + e.Message + "\r堆栈：" + e.StackTrace));
            }
        }

        public void Trace(string trace)
        {
            System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true);
            System.Diagnostics.StackFrame sf = null;

            int count = st.FrameCount;

            for (int i = 0; i < count; i++)
            {
                sf = st.GetFrame(i);

                if (sf.GetFileLineNumber() == 0)
                {
                    continue;
                }

                var declaringType = sf.GetMethod().DeclaringType;
                if (declaringType != null)
                {
                    string className = declaringType.ToString();
                    string methodName = sf.GetMethod().Name;

                    if (className == "WJ.Infrastructure.Log.SystemLog" && methodName == "Trace")
                    {
                        continue;
                    }
                }

                logList.Add(
                    new LogItem(trace + "\r类：" + sf.GetMethod().DeclaringType + "；方法：" + sf.GetMethod().Name + "；行号：" +
                                sf.GetFileLineNumber()));

            }
        }

        public void Message(string message)
        {
            logList.Add(new LogItem(message));
        }

        public void Save()
        {
            if (SaveMode != null)
            {
                SaveMode(logList);
            }
        }
    }


    public class LogItem
    {

        public DateTime Time { get; set; }

  
        public string Message { get; set; }

        public LogItem(string message)
        {
            Time = DateTime.Now;
            Message = message;
        }
    }
}